# 贪吃蛇_pygame.py
import pygame
import sys
import random

pygame.init()
window = pygame.display.set_mode((500,500))
textFont = pygame.font.Font(None,30)
clock = pygame.time.Clock()
 
direction = "left"
speed = 20
FPS = 4
head = [200,200]
body = [[head[0]+speed,head[1]]]
GameOver = False
apples = []
def createApple():
	while True:
		newApple = [random.randint(0,500-speed)//speed*speed,random.randint(0,500-speed)//speed*speed]
		if newApple not in apples and newApple != head and newApple not in body:
			apples.append(newApple)
			break

def paint():
	global GameOver
	body.insert(0,[head[0],head[1]])
	if direction=="left":
		head[0]-=speed
	elif direction=="right":
		head[0]+=speed
	elif direction=="up":
		head[1]-=speed
	elif direction=="down":
		head[1]+=speed
	if head[0]<0 or head[0]>500-speed or head[1]<0 or head[1]>500-speed or head in body:
		GameOver = True
	if head not in apples:
		body.pop(-1)
	else:
		apples.remove(head)
		createApple()
	if not GameOver:
		pygame.draw.rect(window,(200,200,200),(head,(speed,speed)))
		for pos in body:
			pygame.draw.rect(window,(255,255,255),(pos,(speed,speed)))
		for apple in apples:
			pygame.draw.rect(window,(255,0,0),(apple,(speed,speed)))

createApple()
while True:
	window.fill((0,0,0))
	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			sys.exit()
		elif event.type == pygame.KEYDOWN:
			if event.key == pygame.K_a:
				direction = "left"
			elif event.key == pygame.K_d:
				direction = "right"
			elif event.key == pygame.K_s:
				direction = "down"
			elif event.key == pygame.K_w:
				direction = "up"
	if GameOver:
		textFont = pygame.font.Font(None,60)
		textSurface = textFont.render("GameOver!  score:%d"%(len(body)-1),True,(255,255,255))
		window.blit(textSurface,(35,200))
	else:
		paint()
	pygame.display.update()
	clock.tick(FPS)
pygame.quit()